let addPolygon = []; // 记录绘制过程中的面实体
function draw() {
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  let movePosition = []; // 记录绘制过程中移动的点位置
  let moveEntity = null; // 记录绘制过程中移动的点实体
  let positions = []; // 记录左键点击的点位置
  let polygonEntity = null; // 记录面实体
  let pointEntities = []; // 记录左键点击的点实体

  // 鼠标移动事件
  handler.setInputAction(event => {
    moveEntity && viewer.entities.remove(moveEntity);
    movePosition = [];
    movePosition.push(changeToThree(event.endPosition));
    moveEntity = viewer.entities.add({
      position: movePosition[0],
      point: {
        pixelSize: 8,
        color: Cesium.Color.fromCssColorString('#0290F2').withAlpha(0.7),
      },
    });
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    
  // 点击左键事件
  handler.setInputAction(event => {
    positions.push(changeToThree(event.position));
    if (positions.length === 1) {
      polygonEntity = viewer.entities.add({
        polygon: {
          hierarchy: new Cesium.CallbackProperty(function() {
            return new Cesium.PolygonHierarchy(positions.concat(movePosition));
          }, false),
          material: Cesium.Color.fromCssColorString('#0290F2').withAlpha(0.25),
        },
        polyline: {
          positions: new Cesium.CallbackProperty(function() {
            return positions.concat(movePosition).concat([positions[0]]);
          }, false),
          material: Cesium.Color.fromCssColorString('#0290F2'),
          clampToGround: true,
          width: 3,
        },
      });
    }
    const pointEntitiy = viewer.entities.add({
      position: changeToThree(event.position),
      point: {
        pixelSize: 8,
        color: Cesium.Color.fromCssColorString('#0290F2').withAlpha(0.7),
      },
    });
    pointEntities.push(pointEntitiy);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 点击右键事件
  handler.setInputAction(() => {
    pointEntities.forEach(item => {
      viewer.entities.remove(item);
    });
    if (positions.length >= 3) {
      addPolygon.push(polygonEntity);
      // 将最终的面信息保存起来,为了将面的位置信息保存起来
      // polygonEntity.polygon.hierarchy = positions;
      const polygon = turf.polygon([changeToLnglgt(positions.concat(positions[0]))]);
      const S = turf.area(polygon);
      const lineString = turf.lineString(changeToLnglgt(positions.concat(positions[0])));
      const C = turf.length(lineString);
      console.log(`该测区的面积为${S / 1000000}km^2, 该测区的周长为${C}km`)
    } else {
      viewer.entities.remove(polygonEntity);
    };
    movePosition = []; // 控制最后右键点击的点是否保留
    viewer.entities.remove(moveEntity);
    
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

function clearAll() {
  addPolygon.forEach(item => {
    viewer.entities.remove(item);
  });
};
